package com.ekuaitu.kuaitu.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.bean.AlipayPreBean;
import com.ekuaitu.kuaitu.bean.MemberCardDetailBean;
import com.ekuaitu.kuaitu.bean.MemberCardListBean;
import com.ekuaitu.kuaitu.bean.MemberPayResultEvent;
import com.ekuaitu.kuaitu.bean.WXPreBean;
import com.ekuaitu.kuaitu.payment.AlipayUtils;
import com.ekuaitu.kuaitu.payment.WXPayUtils;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.TimeUtils;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MemberActivity extends BaseActivity {


    @BindView(R.id.member_ok_type)
    TextView memberOkType;
    @BindView(R.id.member_ok_time)
    TextView memberOkTime;
    @BindView(R.id.member_month_money)
    TextView memberMonthMoney;
    @BindView(R.id.member_quarter_money)
    TextView memberQuarterMoney;
    @BindView(R.id.member_layout_ok)
    LinearLayout memberLayoutOk;
    @BindView(R.id.member_button_month)
    RadioButton memberButtonMonth;
    @BindView(R.id.member_button_quarter)
    RadioButton memberButtonQuarter;
    @BindView(R.id.member_button_wx)
    RadioButton memberButtonWx;
    @BindView(R.id.member_button_zfb)
    RadioButton memberButtonZfb;
    @BindView(R.id.member_pay_line)
    View memberPayLine;
    @BindView(R.id.member_pay_wx)
    RelativeLayout memberPayWx;
    @BindView(R.id.member_pay_zfb)
    RelativeLayout memberPayZfb;

    @BindView(R.id.member_layout_no)
    LinearLayout memberLayoutNo;
    @BindView(R.id.member_scroll)
    ScrollView memberScroll;
    @BindView(R.id.progress_bar_member)
    RelativeLayout progressBarMember;
    private Context mContext = this;
    private int memberType;
    private String monthCardId;
    private String quarterCardId;
    private int payMethod = 0;

    @Override

    public int getLayoutId() {
        return R.layout.activity_member;
    }


    @Override
    public void initData() {
        super.initData();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        memberType = getIntent().getIntExtra("memberType", 0);
    }

    @Override
    public void initView() {
        if (memberType == 0) {  //没有优惠卡
            //显示可用的支付方式
            if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 1 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 1) {
                memberPayWx.setVisibility(View.VISIBLE);
                memberPayZfb.setVisibility(View.VISIBLE);
                memberPayLine.setVisibility(View.VISIBLE);
                memberButtonWx.setChecked(true);
                memberButtonZfb.setChecked(false);
                payMethod = 1;
            } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 1 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 0) {
                memberPayWx.setVisibility(View.VISIBLE);
                memberPayZfb.setVisibility(View.GONE);
                memberPayLine.setVisibility(View.GONE);
                memberButtonWx.setChecked(true);
                memberButtonZfb.setChecked(false);
                payMethod = 1;
            } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 0 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 1) {
                memberPayWx.setVisibility(View.GONE);
                memberPayZfb.setVisibility(View.VISIBLE);
                memberPayLine.setVisibility(View.GONE);
                memberButtonWx.setChecked(false);
                memberButtonZfb.setChecked(true);
                payMethod = 2;
            } else {
                memberPayWx.setVisibility(View.GONE);
                memberPayZfb.setVisibility(View.GONE);
                memberPayLine.setVisibility(View.GONE);
                payMethod = 0;
            }
            memberButtonZfb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {
                        payMethod = 2;
                        memberButtonWx.setChecked(false);
                    }
                }
            });
            memberButtonWx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {
                        payMethod = 1;
                        memberButtonZfb.setChecked(false);
                    }
                }
            });
            getMemberCarList();    //未购买卡，获取要购买卡的ID等
        } else {
            getMemberCardDetail();  //已购买卡的详情
        }
    }

    //已购买卡的详情

    private void getMemberCardDetail() {
        progressBarMember.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getMemberCardDetail(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<MemberCardDetailBean>() {
            @Override
            public void onResponse(Call<MemberCardDetailBean> call, Response<MemberCardDetailBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    progressBarMember.setVisibility(View.GONE);
                    switch (response.body().getStatus()) {
                        case "200":
                            if (response.body().getAttachment().getUserConcessionCardModel().getConcessionCardType() == 1) {
                                memberOkType.setText("您已购买月卡");
                            } else {
                                memberOkType.setText("您已购买季卡");
                            }
                            String startTime = TimeUtils.getFormatDate(response.body().getAttachment().getUserConcessionCardModel().getStartTime(), " yyyy-MM-dd");
                            String endTime = TimeUtils.getFormatDate(response.body().getAttachment().getUserConcessionCardModel().getEndTime(), " yyyy-MM-dd");
                            memberOkTime.setText("有效期: " + startTime + "至" + endTime);
                            memberLayoutOk.setVisibility(View.VISIBLE);
                            memberLayoutNo.setVisibility(View.GONE);
                            break;
                        case "400":
                            memberLayoutOk.setVisibility(View.GONE);
                            memberLayoutNo.setVisibility(View.VISIBLE);
                            ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            break;
                        default:
                            ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            break;
                    }
                } else {
                    progressBarMember.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<MemberCardDetailBean> call, Throwable t) {
                progressBarMember.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });

    }


    //未购买卡，获取要购买卡的ID等
    private void getMemberCarList() {
        progressBarMember.setVisibility(View.VISIBLE);
        String areaCode = MyApplication.getInstance().getAreaCode();
        if (areaCode == null) {
            areaCode = "";
        }
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getMemberCardList(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<MemberCardListBean>() {
            @Override
            public void onResponse(Call<MemberCardListBean> call, Response<MemberCardListBean> response) {
                progressBarMember.setVisibility(View.GONE);
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus().equals("200") && response.body().getAttachment().getKuaituConcessionCardModels().size() != 0) {
                        monthCardId = response.body().getAttachment().getKuaituConcessionCardModels().get(0).getId();
                        quarterCardId = response.body().getAttachment().getKuaituConcessionCardModels().get(1).getId();
                        memberMonthMoney.setText("¥" + response.body().getAttachment().getKuaituConcessionCardModels().get(0).getAmount());
                        memberQuarterMoney.setText("¥" + response.body().getAttachment().getKuaituConcessionCardModels().get(1).getAmount());
                        //初始化View
                        memberLayoutOk.setVisibility(View.GONE);
                        memberLayoutNo.setVisibility(View.VISIBLE);
                        memberButtonMonth.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                                if (b) {
                                    memberButtonQuarter.setChecked(false);
                                }
                            }
                        });
                        memberButtonQuarter.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                                if (b) {
                                    memberButtonMonth.setChecked(false);
                                }
                            }
                        });
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBarMember.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<MemberCardListBean> call, Throwable t) {
                progressBarMember.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Subscribe
    public void onPayResult(MemberPayResultEvent event) {
        if (event.payResult == 0) {
            //支付成功
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //再次刷新请求信息
                    getMemberCardDetail();
                }
            }, 4000);
        } else {
            progressBarMember.setVisibility(View.GONE);
        }

    }

    private void payMember(String memberCard) {
        if (payMethod == 1) {
            getWXpayParams(memberCard);
        } else if (payMethod == 2) {
            getAlipayParams(memberCard);
        }
    }

    private void getWXpayParams(String memberCard) {
        String areaCode = MyApplication.getInstance().getAreaCode();
        progressBarMember.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).weChatMemberCardBuy(MyApplication.getInstance().getRequestFieldMap(), "2", memberCard).enqueue(new Callback<WXPreBean>() {
            @Override
            public void onResponse(Call<WXPreBean> call, Response<WXPreBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 5);
                        WXPreBean.AttachmentBean.BeanBean orderInfo = response.body().getAttachment().getBean();
                        WXPayUtils wxPayUtils = new WXPayUtils(mContext);
                        wxPayUtils.wxPay(orderInfo);
                    } else {
                        progressBarMember.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBarMember.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<WXPreBean> call, Throwable t) {
                progressBarMember.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void getAlipayParams(String memberCard) {
        String areaCode = MyApplication.getInstance().getAreaCode();
        progressBarMember.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).aliPayMemberCardBuy(MyApplication.getInstance().getRequestFieldMap(), "1", memberCard)
                .enqueue(new Callback<AlipayPreBean>() {
                    @Override
                    public void onResponse(Call<AlipayPreBean> call, Response<AlipayPreBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 5);
                                String orderInfo = response.body().getAttachment().getStr();
                                AlipayUtils alipayUtils = new AlipayUtils(MemberActivity.this);
                                alipayUtils.aliPay(orderInfo);
                            } else {
                                progressBarMember.setVisibility(View.GONE);
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                            }
                        } else {
                            progressBarMember.setVisibility(View.GONE);
                            ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<AlipayPreBean> call, Throwable t) {
                        progressBarMember.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @OnClick({R.id.member_return, R.id.member_ok_start, R.id.member_pay, R.id.member_buy_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.member_return:
                finish();
                break;
            case R.id.member_ok_start:
                Intent intent = new Intent(mContext, MainActivity.class);
                intent.putExtra("isContinue", true);
                startActivity(intent);
                break;
            case R.id.member_pay:
                if (!memberButtonMonth.isChecked() && !memberButtonQuarter.isChecked()) {
                    ToastCompat.makeText(mContext, "请选择卡类型", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (memberButtonMonth.isChecked()) {
                    payMember(monthCardId);
                } else if (memberButtonQuarter.isChecked()) {
                    payMember(quarterCardId);
                } else {
                    ToastCompat.makeText(mContext, "请选择支付方式", Toast.LENGTH_SHORT).show();
                    return;
                }
                break;
            case R.id.member_buy_agreement:
                Intent intent2 = new Intent();
                intent2.setClass(mContext, WebViewActivity.class);
                intent2.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlConstant.Request.BUY_MEMBER_AGREEMENT);
                intent2.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "购买协议");
                startActivity(intent2);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
